<template>
  <a-tabs default-active-key="task">
    <a-tab-pane key="task" title="当前任务">
      <div class="task-count-summary">
        <span class="column-name">进行中</span><span class="column-value">{{ countInprocessTask() }}</span
        ><span class="column-name">待按排</span><span class="column-value">{{ taskGroupList.length }}</span> <span class="column-name">今日完成</span><span class="column-value">{{ countDoneTask() }} </span>
      </div>
      <div class="current-task-layout">
        <div class="accepted-pool">
          <div class="tips">优先级高的任务先做，对于难以完成的请释放回任务市场，对于有疑问的可以找主管协助按排</div>
          <a-table :columns="taskGroupColumnsStyle1" :data="taskGroupList">
            <template #taskGroupSummary="{ record }">
              <div
                ><span class="column-name">发布时间</span><span class="column-value">{{ record.gmtWrite }}</span></div
              >
              <div
                ><span class="column-name">编号</span><span class="column-value">#{{ record.code }}</span></div
              >
              <div
                ><span class="column-name">类型</span
                ><span class="column-value">
                  <span v-if="record.type === 'AMZ_PIC'">制图 (亚马逊)</span>
                  <span v-else>{{ record.type }}</span>
                </span></div
              >
              <div
                ><span class="column-name">任务</span><span class="column-value">{{ record.subject }}</span></div
              >
              <div
                ><span class="column-name">状态</span><span class="column-value">{{ record.status }}</span></div
              >
              <div
                ><span class="column-name">备注</span><span class="column-value">{{ record.creatorRemarks }}</span></div
              >
              <div
                ><span class="column-name">期望完成时间</span><span class="column-value">{{ record.gmtExpectFinish }}</span></div
              >
              <div>
                <a-button type="outline" size="mini" status="success" @click="onTaskStart(record)">加入执行队列 → </a-button>
              </div>
              <div style="margin-bottom: 20px">
                <div><span class="column-name">转给其它人</span></div>
                <div>
                  <a-select size="mini" :style="{ width: '200px' }" placeholder="Please select ..." v-model="record.nextPerson">
                    <a-option v-for="(member, member_index) in members" :key="member_index" :value="member.userId" :label="member.name"></a-option>
                  </a-select>
                  <a-button type="outline" size="mini" status="success" style="margin-top: 5px" @click="onTaskTransfer(record)"> 确认转交</a-button>
                </div>
              </div>
            </template>
          </a-table>
        </div>
        <div class="line-up">
          <div class="ling-up-task-group-layout">
            <div class="tips">执行中的任务队列（今日需要完成）,请从上至下完成，完成了及时上传及报告进度</div>
            <div v-for="(record, index) in taskGroupInProcessList" :key="index" :class="record.status === 'done' ? 'completed-task ling-up-task-group' : 'ling-up-task-group'">
              <div class="done-tag" v-if="record.status === 'done'"> 已完成 </div>
              <div class="summary">
                <div v-if="record.scoreRemarks">
                  <span class="column-name">置顶</span> <span class="important-things">{{ record.scoreRemarks }}</span>
                </div>
                <div
                  ><span class="column-name">任务</span><span class="column-value">{{ record.subject }}</span></div
                >

                <div
                  ><span class="column-name">发布时间</span><span class="column-value">{{ record.gmtWrite }}</span></div
                >
                <div v-if="record.status === 'done'"
                  ><span class="column-name">抢单时间</span><span class="column-value">{{ record.gmtAccepted }}</span></div
                >
                <div
                  ><span class="column-name">期望完成时间</span><span class="column-value">{{ record.gmtExpectFinish }}</span></div
                >
                <div v-if="record.status === 'done'"
                  ><span class="column-name">实际完成时间</span><span class="column-value">{{ record.gmtDone }}</span></div
                >
                <div
                  ><span class="column-name">编号</span><span class="column-value">#{{ record.code }}</span></div
                >
                <div
                  ><span class="column-name">类型</span
                  ><span class="column-value">
                    <span v-if="record.type === 'AMZ_PIC'">制图 (亚马逊)</span>
                    <span v-else>{{ record.type }}</span>
                  </span></div
                >
                <div
                  ><span class="column-name">状态</span><span class="column-value">{{ record.status }}</span></div
                >
                <div
                  ><span class="column-name">发起人</span><span class="column-value">{{ record.creatorUserName }}</span></div
                >
                <div
                  ><span class="column-name">备注</span><span class="column-value">{{ record.creatorRemarks }}</span> <span class="column-name">备注时间</span><span class="column-value">{{ record.creatorRemarksTime }}</span>
                </div>

                <div><span class="column-name">附件(客户上传)</span></div>
                <div>
                  <ul class="attachment-list">
                    <li>ddd</li>
                    <li>ddd</li>
                  </ul>
                </div>
                <div>
                  <div v-if="record.status === 'in-process'"><a-button type="outline" size="mini" status="danger" @click="onTaskHangup(record)"> ← 返回任务池</a-button></div>
                  <div v-if="record.status === 'in-process' && index > 0"><a-button type="outline" size="mini" status="normal" @click="onTop(record)" style="margin-top: 5px"> 置顶↑ </a-button></div>
                  <a-button type="primary" size="mini" status="success" style="margin-top: 5px" @click="onTaskComplete(record)"> 已完成,通知相关人员</a-button>
                </div>
                <div style="margin-bottom: 20px">
                  <div><span class="column-name">转给其它人</span></div>
                  <div>
                    <a-select size="mini" :style="{ width: '200px' }" placeholder="Please select ..." v-model="record.nextPerson">
                      <a-option v-for="(member, member_index) in members" :key="member_index" :value="member.userId" :label="member.name"></a-option>
                    </a-select>
                    <a-button type="outline" size="mini" status="success" style="margin-top: 5px" @click="onTaskTransfer(record)"> 确认转交</a-button>
                  </div>
                </div>
                <div><span class="column-name">团队共享文件</span></div>
                <div>
                  <div class="result-div" v-for="(result, result_index) in record.teamAttachments" :key="result_index">
                    <div v-if="result.fileType === 'image/jpeg'"
                      >{{ result_index + 1 }}、

                      <a :href="result.attachmentFile"><img class="image-attachement" :src="result.resultFile + '?x-oss-process=image/resize,m_lfit,h_200'" /></a> <a-button v-if="record.status === 'in-process'" type="text" @click="onDeleteResult1(record, result)">删除</a-button></div
                    >
                    <div v-else
                      >{{ result_index + 1 }}、<a :href="result.attachmentFile">{{ result.name }}</a> <a-button v-if="record.status === 'in-process'" type="text" @click="onDeleteResult1(record, result)">删除</a-button></div
                    >
                  </div>
                  <div v-if="record.status === 'in-process'">
                    <a-upload :multiple="true" @before-upload="beforeUpload2($event, record)" />
                  </div>
                </div>
              </div>
              <div class="detail">
                <div v-for="(task, task_index) in record.tasks" :key="task_index" class="task-item">
                  <span class="column-name">子任务</span><span class="column-value">{{ task.subject }}</span>
                  <span class="pricetag" v-if="task.budgetPrice">价格:{{ task.budgetPrice }}</span>
                  <div>
                    <span class="column-name">#{{ task.code }} </span><span class="column-name" v-if="record.status === 'in-process'">状态</span><span class="column-value" v-if="record.status === 'in-process'">{{ task.status }}</span> <span class="column-name" v-if="record.status === 'in-process'">进度</span
                    ><a-slider v-if="record.status === 'in-process'" @change="onUpdateProgress($event, task)" style="margin-left: 10px" :default-value="task.progress" :style="{ width: '200px' }" :step="10" :show-ticks="true" />
                  </div>

                  <div class="append-result-layout">
                    <div class="result-div" v-for="(result, result_index) in task.results" :key="result_index">
                      <div v-if="result.fileType === 'image/jpeg'">{{ result_index + 1 }}、<img :src="result.resultFile + '?x-oss-process=image/resize,m_lfit,h_200'" /> <a-button v-if="record.status === 'in-process'" type="text" @click="onDeleteResult(task, result)">删除</a-button></div>
                      <div v-else>{{ result_index + 1 }}、{{ result.name }} <a-button v-if="record.status === 'in-process'" type="text" @click="onDeleteResult(task, result)">删除</a-button></div>
                    </div>
                  </div>
                  <div v-if="record.status === 'in-process'">
                    <a-upload :multiple="true" @before-upload="beforeUpload($event, task)" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-tab-pane>
    <a-tab-pane key="history" title="历史"> Coming soon</a-tab-pane>
  </a-tabs>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import OSS from 'ali-oss'
import { updateAttachments, myTaskGroupSearch, startTask, hangupTask, updateTaskResult, taskComplete, setTaskGroupScore, findTeamMember, transferTask, getStsToken } from '@/api/task'
import { Message } from '@arco-design/web-vue'
let taskGroupList: any = ref([])
let taskGroupInProcessList: any = ref([])
let members: any = ref([])
let taskGroupColumnsStyle1 = [
  {
    title: '任务池',
    slotName: 'taskGroupSummary',
  },
]

let client: any = null

//alert(client)

const loadTaskGroupList = async () => {
  //
  let rs = await myTaskGroupSearch({ statusList: ['accepted', 'in-process', 'hang-up'], containRecentlyComplete: true })
  //taskGroupList.value = rs?.data?.records || [];
  let list1: any = []
  let list2: any = []
  ;(rs?.data?.records || []).forEach((item: any) => {
    //console.log('item', item)
    if (item.status === 'in-process') {
      list1.push(item)
    } else if (item.status === 'done') {
      item.score = 0
      list1.push(item)
    } else {
      list2.push(item)
    }
  })
  taskGroupList.value = list2
  taskGroupInProcessList.value = list1
  tasksort()
}

const tasksort = () => {
  taskGroupList.value = taskGroupList.value.sort((a: any, b: any) => a.score < b.score)
  //TODO Bug Record: I Found The Sort Is Not Working In Chrome, But Is Fine In Firefox
  taskGroupInProcessList.value = taskGroupInProcessList.value.sort((a: any, b: any) => {
    return a.score < b.score
  })
}

/**
 * 上传文件至OSS
 * @param file
 * @param task
 */
const beforeUpload = async (file: File, task: any) => {
  let names = file.name.split('.')
  let type = names[names.length - 1]
  let day = new Date()
  let year = day.getFullYear()
  let month = day.getMonth()
  let filename = day.getTime()
  const result = await client.put(`/task/${year}/${month}/${task.id}/${filename}.${type}`, file)
  if (!task.results) {
    task.results = []
  }
  task.results.push({
    resultFile: result?.url,
    fileType: file.type,
  })

  let rs = await updateTaskResult({ taskId: task.id, resultAppendList: [{ name: file.name, resultFile: result?.url, fileType: file.type }] })
  console.log(result)
  return false
}

const beforeUpload2 = async (file: File, taskGroup: any) => {
  let names = file.name.split('.')
  let type = names[names.length - 1]
  let day = new Date()
  let year = day.getFullYear()
  let month = day.getMonth()
  let filename = day.getTime()
  const result = await client.put(`/task/${year}/${month}/${taskGroup.id}/${filename}.${type}`, file)
  if (!taskGroup.teamAttachments) {
    taskGroup.teamAttachments = []
  }
  taskGroup.teamAttachments.push({
    resultFile: result?.url,
    fileType: file.type,
  })

  let rs = await updateAttachments({ type: 'team_share', appendAttachments: [{ taskGroupId: taskGroup.id, fileType: file.type, name: file.name, attachmentFile: result?.url }] })
  console.log(result)
  return false
}

const onDeleteResult = async (task: any, result: any) => {
  //alert(JSON.stringify(task))
  let rs = await updateTaskResult({ taskId: task.id, resultDelList: [{ id: result.id }] })
  task.results.forEach((item: any, index: any) => {
    if (item.id === result.id) {
      task.results.splice(index, 1)
    }
  })
}

const onDeleteResult1 = async (taskGroup: any, result: any) => {
  //alert(JSON.stringify(task))
  let rs = await updateAttachments({ delAttachments: [{ id: result.id }] })
  taskGroup.teamAttachments.forEach((item: any, index: any) => {
    if (item.id === result.id) {
      taskGroup.teamAttachments.splice(index, 1)
    }
  })
}

const countDoneTask = () => {
  return taskGroupInProcessList.value.filter((item: any) => item.status === 'done').length
}
const countInprocessTask = () => {
  return taskGroupInProcessList.value.filter((item: any) => item.status === 'in-process').length
}

const onTaskStart = async (taskGroup: any) => {
  let rs = await startTask({ taskGroupIdList: [taskGroup.id] })
  Message.success('已加入列队')
  taskGroupList.value.forEach((item: any, index: any) => {
    if (item.id === taskGroup.id) {
      taskGroupList.value.splice(index, 1)
    }
  })
  taskGroup.status = 'in-process'
  taskGroupInProcessList.value.push(taskGroup)
  tasksort()
}

const onTaskHangup = async (taskGroup: any) => {
  let rs = await hangupTask({ taskGroupIdList: [taskGroup.id] })
  Message.success('已返回任务池')
  taskGroupInProcessList.value.forEach((item: any, index: any) => {
    if (item.id === taskGroup.id) {
      taskGroupInProcessList.value.splice(index, 1)
    }
  })
  taskGroupList.value.push(taskGroup)
}

const onTop = async (taskGroup: any) => {
  let v = new Date().getTime()
  await setTaskGroupScore({ scores: [{ taskGroupId: taskGroup.id, score: v }] })
  taskGroup.score = v
  taskGroupInProcessList.value = taskGroupInProcessList.value.sort((a: any, b: any) => a.score < b.score)
}

const onUpdateProgress = async (progress: any, task: any) => {
  let rs = await updateTaskResult({ taskId: task.id, progress: progress })
}

const onTaskComplete = async (taskGroup: any) => {
  let rs = await taskComplete({ taskGroupIdList: [taskGroup.id] })
  taskGroup.status = 'done'
  taskGroup.score = 0
  Message.success('感谢您的努力，已通知相关人员')
  tasksort()
}

const onTaskTransfer = async (taskGroup: any) => {
  let rs = await transferTask({ taskGroupIdList: [taskGroup.id], executeUserId: taskGroup.nextPerson })

  taskGroupInProcessList.value.forEach((item: any, index: any) => {
    if (item.id === taskGroup.id) {
      taskGroupInProcessList.value.splice(index, 1)
    }
  })
  taskGroupList.value.forEach((item: any, index: any) => {
    if (item.id === taskGroup.id) {
      taskGroupList.value.splice(index, 1)
    }
  })

  Message.success('转交成功')
}

const onFindTeamMember = async () => {
  let rs = await findTeamMember()
  members.value = rs?.data?.members
}

onMounted(async () => {
  await loadTaskGroupList()
  await onFindTeamMember()
  let rs = await getStsToken()
  client = new OSS({
    // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
    region: 'oss-cn-shenzhen',
    // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
    accessKeyId: rs?.data?.accessKeyId,
    accessKeySecret: rs?.data?.accessKeySecret,
    // 从STS服务获取的安全令牌（SecurityToken）。
    stsToken: rs?.data?.securityToken,
    // 填写Bucket名称。
    bucket: 'static-erp',
  })
})
</script>

<style lang="less" scoped>
.current-task-table {
  width: 100%;
  border: 1px;
  margin: 10px;
}
.column-name {
  font-weight: bold;
  margin-right: 5px;
}
.column-value {
  color: gray;
}
.task-count-summary {
  margin-left: 10px;
  font-size: 20px;
}
.image-attachement {
  width: 100px;
}
.current-task-layout {
  margin-left: 10px;
  display: flex;
  .accepted-pool {
    width: 500px;
    border-right: 1px dashed rgb(250, 70, 70);
    padding-right: 10px;
  }
  .line-up {
    flex-grow: 1;
  }
}
.task-item-layout {
  background-color: gray;
  height: 100%;
}
.sub-task-item {
  border: 1px solid gray;
}
.ling-up-task-group-layout {
  margin-left: 10px;
  margin-right: 10px;
  .completed-task {
    border-top: 2px solid rgb(112, 112, 112) !important;
    background-color: #eee;
  }
  .done-tag {
    position: absolute;
    border: 2px dashed rgb(142, 145, 142);
    left: 330px;
    top: 100px;
    padding: 10px 30px 10px 30px;
    color: rgb(120, 122, 120);
    transform: rotate(-70deg);
  }
  .ling-up-task-group {
    border-radius: 5px;
    position: relative;
    border: 1px solid gray;
    padding: 10px;
    border-top: 2px solid green;
    margin-bottom: 10px;
    display: flex;
    .summary {
      position: relative;
      width: 400px;
      border-right: 1px dashed gray;
      .attachment-list {
        list-style: decimal;
        margin-left: 20px;
      }
    }
    .detail {
      margin-left: 10px;
      flex-grow: 1;
      .task-item {
        border: 1px solid rgb(219, 216, 216);
        padding: 5px;
        border-bottom: 0px;
        &:last-child {
          border-bottom: 1px solid rgb(219, 216, 216);
          border-bottom-left-radius: 5px;
          border-bottom-right-radius: 5px;
        }
        &:first-child {
          border-top-left-radius: 5px;
          border-top-right-radius: 5px;
        }
      }
      .append-result-layout {
      }
      .result-div {
        img {
          width: 50px;
        }
        margin-right: 5px;
      }
      .append-result {
        border-radius: 3px;
        width: 50px;
        height: 50px;
        font-size: 20px;
        line-height: 50px;
        text-align: center;
      }
    }
  }
}
.tips {
  font-size: 14px;
}
.important-things {
  color: red;
}
.pricetag {
  margin-left: 5px;
  color: rgb(241, 177, 12);
  font-size: 20px;
  background-color: green;
}
</style>